using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using webapi.Models;
using webapi.Models.Database;

namespace webapi.Controllers{
    // 新建文章接口
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ArticleController : ControllerBase{
        // 构造方法注入
        private readonly CnewsContext _context;
        public ArticleController(CnewsContext context){
            _context = context;
        }

        // 自定义请求数据模型
        // AddArticleRequests 自定义model类
        /// <summary>
        /// 创建（新增）文章
        /// </summary>
        [HttpPost]
        public string AddArticle(AddArticleRequests article){
            // 判断参数是否合法
            if(!ModelState.IsValid){
                return "参数错误";
            }

            // 业务逻辑
            // 判断数据库中是否存在该作者
            if (_context.Users.Where(u => u.UserId == article.UserId).Count() == 0){
                return "用户不存在";
            }
            
            Random random = new Random();
            // 实例化Article类，然后将传递的参数赋值给Article类
            var model = new Article();
            model.UserId = article.UserId;
            model.CateId = article.CateId;
            model.ArticleId = random.Next(1, 999);
            model.ArticleTitle = article.ArticleTitle;
            model.ArticleBody = article.ArticleBody;
            model.LikeSum = 0;
            model.WatchSum = 0;

            _context.Articles.Add(model);
            if (_context.SaveChanges() > 0){
                return "文章添加成功";
            }
            return "文章添加失败";
        }

        // 更新文章
        /// <summary>
        /// 更新（编辑）文章 (通过文章id)
        /// </summary>
        [HttpPost]
        public string UpdateArticle(Article article){
            // 判断参数是否合法
            if (!ModelState.IsValid){
                return "参数错误";
            }

            // 业务逻辑
            // 判断数据库中是否存在该作者
            if (_context.Users.Where(u => u.UserId == article.UserId).Count() == 0){
                return "用户不存在";
            }
            // 判断数据库中是否存在该文章
            if (_context.Articles.Where(a => a.ArticleId == article.ArticleId).Count() == 0){
                return "文章不存在";
            }

            // 更新文章
            _context.Articles.Update(article);
            // 判断是否添加成功
            if (_context.SaveChanges() > 0){
                return "文章更新成功";
            }
            return "文章更新失败";
        }

        // 获取文章列表
        /// <summary>
        /// 获取文章列表
        /// </summary>
        [HttpGet]
        public List<Article> GetArticleList(){
            return _context.Articles.ToList();
        }

        // 删除文章(url传参)
        /// <summary>
        /// 删除文章
        /// </summary>
        [HttpPost]
        public string DeleteArticle(int id){
            // 判断参数是否合法
            if (!ModelState.IsValid){
                return "参数错误";
            }
            var article = _context.Articles.Where(a => a.ArticleId == id).FirstOrDefault();
            if (article == null){
                return "文章不存在";
            }
            _context.Articles.Remove(article);
            if (_context.SaveChanges() > 0){
                return "文章删除成功";
            }
            return "文章删除失败";
        }

        //添加文章观看数
        /// <summary>
        /// 添加文章观看数
        /// </summary>
        [HttpPost]
        public string AddArticleWatchSum(int ArticleId, int WatchSum){
            // 判断参数是否合法
            if (!ModelState.IsValid){
                return "参数错误";
            }
            var article = _context.Articles.Where(a => a.ArticleId == ArticleId).FirstOrDefault();
            if (article == null){
                return "文章不存在";
            }
            article.WatchSum += WatchSum;
            _context.Articles.Update(article);
            if (_context.SaveChanges() > 0){
                return "文章观看数添加成功";
            }
            return "文章观看数添加失败";
        }

        // 查询指定文章的所有信息
        /// <summary>
        /// 查询指定文章的所有信息
        /// </summary>
        [HttpGet]
        public GetArticleRespone GetArticleAllInfo(int ArticleId){
            var article = _context.Articles.Where(a => a.ArticleId == ArticleId).FirstOrDefault();
            // 添加其他字段 例如：作者名
            var respone  = new GetArticleRespone();
            respone.UserId = article.UserId;
            respone.UserName = _context.Users.Where(u => u.UserId == article.UserId).FirstOrDefault().UserName;
            respone.CateId = article.CateId;
            respone.CateName = _context.Categories.Where(c => c.CateId == article.CateId).FirstOrDefault().CateName;
            respone.ArticleId = article.ArticleId;
            respone.ArticleTitle = article.ArticleTitle;
            respone.ArticleBody = article.ArticleBody;
            respone.LikeSum = _context.Likes.Where(l => l.ArticleId == article.ArticleId).Count();
            respone.WatchSum = article.WatchSum;
            return respone;
        }
    
        // 查询指定分类下所有文章的观看数
        /// <summary>
        /// 查询指定分类下所有文章的观看数
        /// </summary>
        [HttpGet]
        public long GetArticleWatchSum(int CateId){
            var article = _context.Articles.Where(a => a.CateId == CateId).ToList();
            long sum = 0;
            foreach (var item in article){
                sum +=Convert.ToInt64(item.WatchSum);
            }
            return sum;
        }

        // 根据分类、文章标题和文章内容筛选查询文章数据
        /// <summary>
        /// 根据分类、文章标题和文章内容筛选查询文章数据
        /// </summary>
        [HttpGet]
        public List<Article> GetArticleByCateIdOrArticleTitleOrArticleBody(int CateId, string ArticleTitle, string ArticleBody){
            var article = _context.Articles.Where(a => a.CateId == CateId || a.ArticleTitle.Contains(ArticleTitle) || a.ArticleBody.Contains(ArticleBody)).ToList();
            return article;
        }
    }
}